package com.cao.mianshiya.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.Wrapper;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cao.mianshiya.annotation.AuthCheck;
import com.cao.mianshiya.common.BaseResponse;
import com.cao.mianshiya.common.DeleteRequest;
import com.cao.mianshiya.common.ErrorCode;
import com.cao.mianshiya.common.ResultUtils;
import com.cao.mianshiya.constant.UserConstant;
import com.cao.mianshiya.exception.BusinessException;
import com.cao.mianshiya.exception.ThrowUtils;
import com.cao.mianshiya.model.dto.question.QuestionAddRequest;
import com.cao.mianshiya.model.dto.question.QuestionEditRequest;
import com.cao.mianshiya.model.dto.question.QuestionQueryRequest;
import com.cao.mianshiya.model.dto.question.QuestionUpdateRequest;
import com.cao.mianshiya.model.entity.Question;
import com.cao.mianshiya.model.entity.QuestionBankQuestion;
import com.cao.mianshiya.model.entity.User;
import com.cao.mianshiya.model.vo.QuestionVO;
import com.cao.mianshiya.service.QuestionBankQuestionService;
import com.cao.mianshiya.service.QuestionService;
import com.cao.mianshiya.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 题目接口
 * cao
 * 木叶村
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {
    //题目表服务
    @Resource
    private QuestionService questionService;
    //题目题库关联表服务
    @Resource
    private QuestionBankQuestionService questionBankQuestionService;

    @Resource
    private UserService userService;


    /**
     * 创建题目 [管理员接口]
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        // 补充标签字段数据 -> 因为实体类和dto类的字段不一致
        if (CollectionUtil.isNotEmpty(questionAddRequest.getTags())) {
            question.setTags(JSONUtil.toJsonStr(questionAddRequest.getTags()));
        }
        // 数据校验
        questionService.validQuestion(question, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除题目 [管理员接口]
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新题目（仅管理员可用）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        // 同样补充标签字段转换
        if (CollectionUtil.isNotEmpty(questionUpdateRequest.getTags())) {
            question.setTags(JSONUtil.toJsonStr(questionUpdateRequest.getTags()));
        }
        // 数据校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 编辑题目（给用户使用）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        // 将编辑请求的List<String> tags 转换为 Stirng
        // 同样补充标签字段转换
        if (CollectionUtil.isNotEmpty(questionEditRequest.getTags())) {
            question.setTags(JSONUtil.toJsonStr(questionEditRequest.getTags()));
        }
        // 数据校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionEditRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题目（封装类）[用户接口]
     *
     * @param id : 题目id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Question question = questionService.getById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }


    /**
     * @param questionQueryRequest:题目查询dto类
     * @return: 题目列表接口
     */
    @PostMapping("/getQuestionList")
    @Deprecated
    public BaseResponse<Page<Question>> getQuestionList(@RequestBody QuestionQueryRequest questionQueryRequest) {
        ThrowUtils.throwIf(questionQueryRequest.getQuestionBankId() <= 0, ErrorCode.PARAMS_ERROR);
        QueryWrapper<QuestionBankQuestion> questionBankQuestionQueryWrapper = new QueryWrapper<>();
        //根据题库id封装 查询条件
        questionBankQuestionQueryWrapper.eq("questionBankId", questionQueryRequest.getQuestionBankId());
        questionBankQuestionQueryWrapper.select("questionId"); //查询关联表的时候，不要 select 所有字段，只取 questionId 就够了，可以提升性能
        //根据关联表服务查询对应的数据对象集合
        List<QuestionBankQuestion> questionBankQuestionList = questionBankQuestionService.list(questionBankQuestionQueryWrapper);
        QueryWrapper<Question> questionQueryWrapper = null;
        // 增加判空条件
        if (CollectionUtil.isNotEmpty(questionBankQuestionList)) {
            //根据上述集合取出题目id集合
            Set<Long> questionID = questionBankQuestionList.stream().map(QuestionBankQuestion::getQuestionId).collect(Collectors.toSet());
            //根据题目id查询到所有的题目封装类分页对象返回
            questionQueryWrapper = new QueryWrapper<>();
            //封装查询条件 in 范围查询
            questionQueryWrapper.in("id", questionID);
        }
        //根据QuestionService查询到符合条件的对应对象集合 返回分页对象
        Page<Question> page = questionService.page(new Page<>(questionQueryRequest.getCurrent(), questionQueryRequest.getPageSize()), questionQueryWrapper);
        return ResultUtils.success(page);
    }

    /**
     * 根据题库[id或者题库查询体]查询题目列表接口 [管理员接口] 方案二
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        Page<Question> questionList = questionService.getQuestionList(questionQueryRequest);
        return ResultUtils.success(questionList);
    }

    /**
     * 根据题库[id或者题库查询体]查询题目列表接口 [管理员接口] 方案一 自定义sql实现
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page2")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage2(@RequestBody QuestionQueryRequest questionQueryRequest) {
        Page<Question> questionList = questionService.getQuestionList2(questionQueryRequest);
        return ResultUtils.success(questionList);
    }
    /**
     * 分页获取题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题目列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }


}
